import { Component } from 'react'
import Onec from '../components/Onec'
import Twoc from '../components/Twoc'
class Indexc extends Component {
    constructor() {
        super()
        this.state = {
            list: [
                { name: '胡桃', age: 18, id: 1111 },
                { name: '雷电将军', age: 19, id: 1114 },
                { name: '钟离', age: 25, id: 1112 },
                { name: '枫原万叶', age: 18, id: 1113 },
            ],
            flag: true,
            editId: null,
            name: '',
            age: '',
        }
    }
    stateFn = (n) => {
        // console.log('-----', n);
        this.setState({
            [n.target.name]: n.target.value
        })
    }
    submit = () => {
        let list = JSON.parse(JSON.stringify(this.state.list));
        let n = { name: this.state.name, age: this.state.age, id: +new Date() }
        list.push(n)
        // console.log(list);
        this.setState({
            list: list,
            name: '',
            age: ''
        })
    }
    editBtnc = () => {
        let list = JSON.parse(JSON.stringify(this.state.list));
        let index = list.findIndex(v => v.id === this.state.editId);
        // console.log('----++++', this.state.editId, index);
        console.log();
        list[index].name = this.state.name
        list[index].age = this.state.age
        this.setState({
            list: list,
            flag: true,
            name: '',
            age: ''
        })
    }
    edit = (obje, id) => {
        // console.log('----',id);
        let list = JSON.parse(JSON.stringify(this.state.list));
        let obj = list.find((e, i) => e.id === id)
        console.log('+++++', obj);
        this.setState({
            name: obj.name,
            age: obj.age,
            editId: obj.id,
            flag: false
        })
    }
    delc = (id) => {
        let list = JSON.parse(JSON.stringify(this.state.list))
        let index = list.findIndex((e, i) => e.id === id)
        list.splice(index, 1)
        this.setState({
            list: list
        })
    }
    render() {
        return (
            <div>
                <Onec statec={this.state} stateFn={this.stateFn} submitc={this.submit} editBtnc={this.editBtnc}></Onec>
                <Twoc list={this.state.list} edit={this.edit} delc={this.delc}></Twoc>
            </div>


        )
    }
}

export default Indexc